import { request } from "../../request/index.js";
const regeneratorRuntime = require("../../lib/runtime/runtime.js");
Page({
  data: {
    GoodsObj: {},
    isCollected:false
  },
  GoodsInfo: {},
  onShow: function() {
    var pages =  getCurrentPages();
    let currentPage = pages[pages.length-1]
    let options = currentPage.options
    const { goods_id } = options;
    this.getGoodsDetail(goods_id);
   
  },
  // 获取商品详情数据
  async getGoodsDetail(goods_id) {
    const GoodsObj = await request({
      url: "/goods/detail",
      data: { goods_id }
    });
    this.GoodsInfo = GoodsObj;
     // 获取缓存中收藏商品的数组
     let collect = wx.getStorageSync("collect")||[]
     // 判断当前商品是否被收藏
     let isCollected = collect.some(v=>v.goods_id===this.GoodsInfo.goods_id)
    this.setData({
      GoodsObj: {
        goods_name: GoodsObj.goods_name,
        goods_price: GoodsObj.goods_price,
        // 适配IOS系统 临时设置格式
        goods_introduce: GoodsObj.goods_introduce.replace(/\.webp/g, ".jpg"),
        pics: GoodsObj.pics
      },
      isCollected
    });
  },
  // 图片预览事件
  handlePreviewImage(e) {
    // 构造预览图片数组
    const urls = this.GoodsInfo.pics.map(v => v.pics_mid);
    // 接受传递过来的url
    const current = e.currentTarget.dataset.url;
    wx.previewImage({
      current,
      urls
    });
  },
  // 添加商品到购物车
  handleAddGoods() {
    // 获取缓存中的购物车数据
    let cart = wx.getStorageSync("cart") || [];
    // 判断商品是否已经在购物车中
    let index = cart.findIndex(v => v.goods_id === this.GoodsInfo.goods_id);
    if (index === -1) {
      this.GoodsInfo.num = 1;
      this.GoodsInfo.checked = true;
      cart.push(this.GoodsInfo);
    } else {
      cart[index].num++;
    }
    // 吧数据添加到缓存
    wx.setStorageSync("cart", cart);
    wx.showToast({
      title: "添加成功",
      icon: "success",
      mask: true
    });
  },
  // 添加到收藏
  addCollect(){
    let isCollected = false
    // 获取缓存中的isCollected
    let collect = wx.getStorageSync("collect")||[]
    // 判断商品是否被收藏过
    let index = collect.findIndex(v=>v.goods_id===this.GoodsInfo.goods_id)
    if (index!==-1){
      // 已收藏过 取消收藏
      collect.splice(index,1)
      isCollected = false
      wx.showToast({
        title: "取消收藏成功",
        icon: "success",
        mask: true
      });
    }else{
      // 未收藏
      collect.push(this.GoodsInfo)
      isCollected=true
      wx.showToast({
        title: "收藏成功",
        icon: "success",
        mask: true
      });
    }
    // 吧数组存入缓存
    wx.setStorageSync("collect",collect)
    this.setData({
      isCollected
    })
  }
});
